package com.fd.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.ResourceBundle;
import java.util.Set;

import javax.imageio.ImageIO;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fd.dao.base.common.Condition;
import com.fd.dao.base.common.MultiPartInfo;
import com.fd.dao.base.common.PageInfo;

/***
 * 全局工具类
 * 
 * @author 符冬
 * 
 */
public class MyUtils implements Serializable {

	private static final long serialVersionUID = -7418411330737638858L;

	/**
	 * 得到文件的后缀名<br/>
	 * System.out.println(getFileSubString("fudong.jpg"));>>>.jpg
	 * 
	 * @param fileName
	 * @return
	 */
	public static String getFileSubString(String fileName) {
		if (fileName != null && fileName.indexOf(".") != -1) {
			return fileName.substring(fileName.indexOf("."));
		}
		return "";
	}

	/**
	 * 判断字符串是否包含内容
	 * 
	 */
	public static boolean isNotEmpty(String str) {
		return str != null && !str.trim().equals("");
	}

	/**
	 * 判断数字是否大于零
	 * 
	 */
	public static boolean isGtZero(Long ls) {
		return ls != null && ls > 0;
	}

	/**
	 * 判断数字是否大于零
	 * 
	 */
	public static boolean isGtZero(Integer ls) {
		return ls != null && ls > 0;
	}

	/**
	 * 随机count位数字字符串<br/>
	 * 可以用来生成代金券号码和密码
	 * 
	 * @param count
	 *            随机多少位
	 */
	public static String getRandomString(int count) {
		if (count > 0) {
			StringBuilder buf = new StringBuilder();
			Random rd = new Random();
			for (int i = 0; i < count; i++) {
				buf.append(rd.nextInt(10));
			}
			return buf.toString();
		} else {
			return "";
		}

	}

	/**
	 * 隐藏字符串中部分敏感信息
	 * 
	 * @param tg
	 *            目标字符串
	 * @param start
	 *            开始索引
	 * @param end
	 *            结束索引
	 * @return
	 */
	public static String hidepartChar(String tg, int start, int end) {
		return new StringBuffer(tg).replace(start, end, "**").toString();
	}

	/**
	 * 判断字符在字符串中出现的次数
	 * 
	 * @param tg
	 * @param fg
	 * @return
	 */
	public static Integer getCountInStr(String tg, char fg) {
		if (isNotEmpty(tg)) {
			int i = 0;
			if (isNotEmpty(tg)) {
				char ch[] = tg.toCharArray();
				for (char c : ch) {
					if (c == fg) {
						i++;
					}
				}
			}
			return i;
		}
		return 0;
	}

	/***
	 * 对象数组转换成对象集合
	 * 
	 * @param <T>
	 * @param ts
	 * @return
	 */
	public static <T> List<T> getList(T... ts) {
		return Arrays.asList(ts);
	}

	/**
	 * 得到long类型集合 如果遇到不能转换为long类型的字符串跳过 返回能转换为long类型的long类型集合
	 * 
	 * @param strings
	 * @return
	 */
	public static List<Long> getListByStrs(String... strings) {
		List<Long> list = new ArrayList<Long>();
		if (strings != null) {
			for (String s : strings) {
				try {
					if (isNotEmpty(s)) {
						list.add(Long.valueOf(s));
					}
				} catch (NumberFormatException e) {
				}
			}
		}
		return list;
	}

	/**
	 * 把首字母变成大写
	 * 
	 * @param str要转换的字符串
	 * @return
	 */
	public static String toUpcaseFist(String str) {
		if (str != null && !str.trim().equals("")) {
			if (str.length() == 1) {
				return str.toUpperCase();
			} else {
				return str.substring(0, 1).toUpperCase() + str.substring(1);
			}
		} else {
			return "";
		}

	}

	/**
	 * 根据键值对得到map<String,Object>对象
	 * 
	 * @param ag
	 * @return
	 */
	public static LinkedHashMap<String, Object> getMap(Object... ag) {
		LinkedHashMap<String, Object> mp = new LinkedHashMap<String, Object>();
		if (ag != null && ag.length > 0 && ag.length % 2 == 0) {
			int i = 0;
			for (Object o : ag) {
				mp.put(String.valueOf(ag[i]), ag[++i]);
				i++;
				if (i == ag.length) {
					break;
				}

			}
		}
		return mp;
	}

	/**
	 * 根据键值对得到map<String,String>对象
	 * 
	 * @param ag
	 * @return
	 */
	public static LinkedHashMap<String, String> getStrValueMap(String... ag) {
		LinkedHashMap<String, String> mp = new LinkedHashMap<String, String>();
		if (ag != null && ag.length > 0 && ag.length % 2 == 0) {
			int i = 0;
			for (String o : ag) {
				mp.put(ag[i], ag[++i]);
				i++;
				if (i == ag.length) {
					break;
				}

			}
		}
		return mp;
	}

	/**
	 * 获得Long类型的attribute
	 * 
	 * @param req
	 * @param attribute
	 * @param dv
	 * @return
	 */
	public static Long getLongAttribute(HttpServletRequest req,
			String attribute, long dv) {
		Object obj = req.getAttribute(attribute);
		if (obj == null || obj.equals("")) {
			return dv;
		}
		try {
			return Long.parseLong(obj.toString());
		} catch (NumberFormatException e) {
			return dv;
		}
	}

	/**
	 * 获得LONG类型的请求参数
	 * 
	 * @param req
	 * @param param
	 * @param dv缺省值
	 * @return
	 */
	public static Long getLongParameter(HttpServletRequest req, String param,
			long dv) {
		String v = req.getParameter(param);
		if (v == null || v.trim().equals("")) {
			return dv;
		}
		try {
			return Long.valueOf(v);
		} catch (NumberFormatException e) {
			return dv;
		}

	}

	/**
	 * 获得LONG类型的请求参数
	 * 
	 * @param req
	 * @param param
	 * @param dv缺省值为0
	 * @return
	 */
	public static Long getLongParameter(HttpServletRequest req, String param) {
		return getLongParameter(req, param, 0);
	}

	/**
	 * 获取字符串类型的请求参数
	 * 
	 * @param req
	 * @param param
	 * @param dv缺省值
	 * @return
	 */
	public static String getStringParameter(HttpServletRequest req,
			String param, String dv) {
		String str = req.getParameter(param);
		if (str == null || str.trim().equals("")) {
			return dv;
		}
		return str.trim();
	}

	/**
	 * 获取字符串类型的请求参数
	 * 
	 * @param req
	 * @param param
	 * @param dv缺省值
	 * @return
	 */
	public static String getStringParameter(HttpServletRequest req, String param) {
		String str = req.getParameter(param);
		if (str == null || str.trim().equals("")) {
			return "";
		}
		return str.trim();
	}

	/**
	 * 获取Integer类型的请求参数
	 * 
	 * @param req
	 * @param param
	 * @param dv缺省值
	 * @return
	 */
	public static Integer getIntegerParameter(HttpServletRequest req,
			String param, Integer dv) {
		String v = req.getParameter(param);
		if (v == null || v.trim().equals("")) {
			return dv;
		}
		try {
			return Integer.valueOf(v);
		} catch (NumberFormatException e) {
			return dv;
		}

	}

	/**
	 * 得到double类型请求参数
	 * 
	 * @param req
	 * @param param
	 * @param dv
	 * @return
	 */
	public static Double getDoubleParameter(HttpServletRequest req,
			String param, double dv) {
		String v = req.getParameter(param);
		if (isNotEmpty(v)) {
			try {
				return Double.valueOf(v);
			} catch (NumberFormatException e) {
			}
		}
		return dv;
	}

	/**
	 * 获取Float类型的请求参数
	 * 
	 * @param req
	 * @param param
	 * @param dv缺省值
	 * @return
	 */
	public static Float getFloatParameter(HttpServletRequest req, String param,
			float dv) {
		String v = req.getParameter(param);
		if (v == null || v.trim().equals("")) {
			return dv;
		}
		try {
			return Float.valueOf(v);
		} catch (NumberFormatException e) {
			return dv;
		}

	}

	/**
	 * 动态图像转换成静态图片
	 * 
	 * @param file图片文件
	 */
	public static void convertImageToStatic(File file) {
		if (file != null) {
			try {
				BufferedImage bufferedimage = ImageIO.read(file);
				if (bufferedimage != null) {
					ImageIO.write(bufferedimage, "gif", file);// 1131.gif是静态的
				}
			} catch (IOException e) {
			}
		}
	}

	/**
	 * 得到用户的IP地址
	 * 
	 * @param req
	 * @return
	 */
	public static String getUserIp(HttpServletRequest req) {
		return req.getRemoteAddr();
	}

	/**
	 * 判断是否为数字
	 * 
	 * @param tg
	 * @return
	 */
	public static Boolean isNumber(String tg) {
		if (isNotEmpty(tg)) {
			try {
				Double.valueOf(tg);
				return true;
			} catch (NumberFormatException e) {
			}
		}
		return false;
	}

	/**
	 * 处理浮点数相加运算
	 * 
	 * @param v
	 * @param v2
	 * @return
	 */
	public static Double floatAdd(Double v, Double v2) {
		BigDecimal b1 = new BigDecimal(Double.toString(v));
		BigDecimal b2 = new BigDecimal(Double.toString(v2));
		return b1.add(b2).doubleValue();
	}

	/**
	 * 处理浮点数相减运算
	 * 
	 * @param v
	 *            被减数
	 * @param v2
	 *            减数
	 * @return
	 */
	public static Double floatSubtract(Double v, Double v2) {
		BigDecimal b1 = new BigDecimal(Double.toString(v));
		BigDecimal b2 = new BigDecimal(Double.toString(v2));
		return b1.subtract(b2).doubleValue();
	}

	/**
	 * 处理浮点数相除
	 * 
	 * @param v
	 * @param v2
	 * @return
	 */
	public static Double floatDiv(Double v, Double v2) {
		BigDecimal b1 = new BigDecimal(Double.toString(v));
		BigDecimal b2 = new BigDecimal(Double.toString(v2));
		return b1.divide(b2).doubleValue();
	}

	/**
	 * 处理浮点数相乘
	 * 
	 * @param v
	 * @param v2
	 * @return
	 */
	public static Double floatMulply(Double v, Double v2) {
		BigDecimal b1 = new BigDecimal(Double.toString(v));
		BigDecimal b2 = new BigDecimal(Double.toString(v2));
		return b1.multiply(b2).doubleValue();
	}

	/**
	 * 判断集合是否不为空
	 * 
	 * @param list
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static Boolean isNotEmpty(Collection list) {
		return list != null && list.size() > 0;
	}

	/**
	 * 判断数组是否不为空
	 * 
	 * @param arr
	 * @return
	 */
	public static Boolean isNotEmptyArr(Object[] arr) {
		return arr != null && arr.length > 0;
	}

	/**
	 * 得到查询条件集合
	 * 
	 * @param conditions
	 * @return
	 */
	public static Set<Condition> getConditions(Condition... conditions) {
		Set<Condition> condi = new HashSet<Condition>();
		if (isNotEmptyArr(conditions)) {
			for (Condition e : conditions) {
				condi.add(e);
			}
		}
		return condi;
	}

	/****
	 * 多表链接查询关联信息
	 * 
	 * @param mpis
	 * @return
	 */
	public static List<MultiPartInfo> getMultiPartInfos(MultiPartInfo... mpis) {
		return Arrays.asList(mpis);
	}

	/****************************************** 华丽分割线 *******************************************************/
	/**
	 * jndi配置信息
	 */
	private static ResourceBundle JNDI;
	/**
	 * JNDI上下文初始化
	 */
	public static InitialContext init;

	// 初始化环境变量
	private static void initJNDI() {
		try {
			JNDI = ResourceBundle.getBundle("jndi");
			Properties prop = new Properties();
			prop.put(Context.INITIAL_CONTEXT_FACTORY,
					JNDI.getObject(Context.INITIAL_CONTEXT_FACTORY));
			prop.put(Context.PROVIDER_URL, JNDI.getObject(Context.PROVIDER_URL));
			init = new InitialContext(prop);
		} catch (NamingException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 得到远程访问EJB会话bean对象
	 * 
	 * @param <T>
	 * @param name
	 *            jndi名称：例如：InventoryDao/remote 返回IInventoryDao的实现类的对象
	 * @return 如果不存在返回null
	 */
	public static <T> T getRemoteObjectByJndiName(String name) {
		try {
			if (init == null) {
				initJNDI();
			}
			return (T) init.lookup(name);
		} catch (NamingException e) {
			e.printStackTrace();
		}
		return null;
	}

	/******************* 华丽分割线 ****************************************************************/

	/**
	 * 对页面显示内容进行编码
	 * 
	 * @param str
	 * @return
	 */
	public static String htmlEncoding(String str) {
		StringBuffer bfu = new StringBuffer();
		if (str != null) {
			String s = "&#";
			char[] cs = str.toCharArray();
			for (char c : cs) {
				int it = c;
				bfu.append(s).append(it).append(";");
			}
		}
		return bfu.toString();

	}

	/**
	 * 得到json数据格式
	 * 
	 * @param flag
	 *            obj[key] key数组
	 * @param property
	 *            name,age..对象属性数组
	 * @param values
	 *            fudong,22.对象属性对应的值
	 * @return
	 */
	public static StringBuffer getJson(String[] flag, String[] property,
			List<String[]> values) {
		StringBuffer buf = new StringBuffer();
		if (flag != null && property != null && property.length > 0) {
			if (values != null && values.size() > 0
					&& property.length == values.get(0).length
					&& values.size() == flag.length) {
				Iterator<String[]> ite = values.iterator();
				buf.append("({");
				for (int j = 0; j < flag.length; j++) {
					buf.append("\"").append(flag[j]).append("\"").append(":");
					String[] ss = ite.next();
					buf.append("{");
					for (int i = 0; i < property.length; i++) {
						buf.append(property[i]).append(":").append("\"")
								.append(ss[i]).append("\"");
						if (property.length - 1 > i) {
							buf.append(",");
						}
					}
					buf.append("}");
					if (ite.hasNext()) {
						buf.append(",");
					}
				}
				buf.append("})");
			}

		}
		return buf;
	}

	/**
	 * 获取用户请求的URI和请求参数
	 * 
	 * @param req
	 * @return 2011-1-4 符冬
	 */
	public static String getRequestURIAndQueryString(HttpServletRequest req) {
		return req.getRequestURI()
				+ (req.getQueryString() == null ? "" : "?"
						+ req.getQueryString());

	}

	/**
	 * 获取用户请求的URL和请求参数
	 * 
	 * @param req
	 * @return 2011-1-4 符冬
	 */
	public static String getRequestURLAndQueryString(HttpServletRequest req) {
		return req.getRequestURL()
				+ (req.getQueryString() == null ? "" : "?"
						+ req.getQueryString());

	}

	/**
	 * 添加cookie
	 * 
	 * @param res
	 * @param maxAge
	 *            单位：秒
	 * @param key
	 * @param value
	 */
	public static void addCookie(HttpServletResponse res, int maxAge,
			String key, String value) {
		Cookie ck = new Cookie(key, value);
		ck.setPath("/");
		if (maxAge > 0) {
			ck.setMaxAge(maxAge);
		}
		res.addCookie(ck);
	}

	/**
	 * 添加cookie
	 * 
	 * @param res
	 * @param maxAge
	 *            单位：秒
	 * @param key
	 * @param value
	 */
	public static void addCookie(HttpServletResponse res, int maxAge,
			String key, String value, String domain) {
		Cookie ck = new Cookie(key, value);
		ck.setPath("/");
		if (maxAge > 0) {
			ck.setMaxAge(maxAge);
		}
		ck.setDomain(domain);
		res.addCookie(ck);
	}

	/**
	 * 添加cookie
	 * 
	 * @param res
	 * @param maxAge
	 *            单位：秒
	 * @param key
	 * @param value
	 */
	public static void addCookie(HttpServletResponse res, String key,
			String value) {
		Cookie ck = new Cookie(key, value);
		ck.setPath("/");
		res.addCookie(ck);
	}

	/**
	 * 添加cookie
	 * 
	 * @param res
	 * @param maxAge
	 *            单位：秒
	 * @param key
	 * @param value
	 */
	public static void addCookie(HttpServletResponse res, String key,
			String value, String domain) {
		Cookie ck = new Cookie(key, value);
		ck.setPath("/");
		ck.setDomain(domain);
		res.addCookie(ck);
	}

	/**
	 * 删除Cookie
	 * 
	 * @param req
	 * @param res
	 * @param key
	 */
	public static void removeCookie(HttpServletRequest req,
			HttpServletResponse res, String key) {
		if (key != null) {
			String v = getCookieValue(req, key);
			if (isNotEmpty(v)) {
				Cookie cks = getCookie(req, key);
				cks.setPath("/");
				cks.setMaxAge(0);
				res.addCookie(cks);
			}
		}
	}

	/**
	 * 删除Cookie
	 * 
	 * @param req
	 * @param res
	 * @param key
	 */
	public static void removeCookie(HttpServletRequest req,
			HttpServletResponse res, String key, String domain) {
		if (key != null) {
			String v = getCookieValue(req, key);
			if (isNotEmpty(v)) {
				Cookie cks = getCookie(req, key);
				cks.setPath("/");
				cks.setDomain(domain);
				cks.setMaxAge(0);
				res.addCookie(cks);
			}
		}
	}

	/**
	 * 得到cookie的值
	 * 
	 * @param req
	 * @param key
	 * @return 没有返回：""
	 */
	public static String getCookieValue(HttpServletRequest req, String key) {
		Cookie ck = getCookie(req, key);
		if (ck != null) {
			return ck.getValue();
		}
		return "";
	}

	/***
	 * 得到cookie对象
	 * 
	 * @param request
	 * @param name
	 * @return
	 */
	public static Cookie getCookie(HttpServletRequest request, String name) {
		Cookie cookies[] = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (name.equals(cookie.getName())) {
					return cookie;
				}
			}
		}
		return null;
	}

	public static <T> PageInfo<T> convert2VO(PageInfo data, Class<T> clazz,
			String... targetProperty) {
		if (data != null && targetProperty.length > 0
				&& data.getDataList().size() > 0) {
			List<T> dataList = new ArrayList<T>();
			if (!(data.getDataList().get(0) instanceof Object[])) {
				String p = targetProperty[0];
				for (Object o : data.getDataList()) {
					try {
						T obj = (T) clazz.newInstance();
						Field fd = clazz.getDeclaredField(p);
						fd.setAccessible(true);
						fd.set(obj, o);
						dataList.add(obj);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

			} else {
				for (Object os : data.getDataList()) {
					Object[] oss = (Object[]) os;
					try {
						T obj = (T) clazz.newInstance();
						for (int i = 0; i < targetProperty.length; i++) {
							Field fd = clazz
									.getDeclaredField(targetProperty[i]);
							fd.setAccessible(true);
							if (oss[i] instanceof BigDecimal) {
								if (fd.getType().equals(Double.class)) {
									fd.set(obj,
											((BigDecimal) oss[i]).doubleValue());
								} else if (fd.getType().equals(double.class)) {

									fd.set(obj,
											((BigDecimal) oss[i]).doubleValue());

								} else if (fd.getType().equals(byte.class)) {

									fd.set(obj,
											((BigDecimal) oss[i]).byteValue());

								} else if (fd.getType().equals(Byte.class)) {

									fd.set(obj,
											((BigDecimal) oss[i]).byteValue());

								} else if (fd.getType().equals(long.class)) {

									fd.set(obj,
											((BigDecimal) oss[i]).longValue());

								} else if (fd.getType().equals(float.class)) {

									fd.set(obj,
											((BigDecimal) oss[i]).floatValue());

								} else if (fd.getType().equals(Float.class)) {
									fd.set(obj,
											((BigDecimal) oss[i]).floatValue());
								} else if (fd.getType().equals(Long.class)) {
									fd.set(obj,
											((BigDecimal) oss[i]).longValue());
								} else if (fd.getType().equals(Integer.class)) {
									fd.set(obj,
											((BigDecimal) oss[i]).intValue());
								} else if (fd.getType().equals(int.class)) {
									fd.set(obj,
											((BigDecimal) oss[i]).intValue());
								} else if (fd.getType().equals(Boolean.class)
										|| fd.getType().equals(boolean.class)) {
									if (((BigDecimal) oss[i]).intValue() == 1) {
										fd.set(obj, true);
									} else {
										fd.set(obj, false);
									}
								} else {
									fd.set(obj, oss[i]);
								}
							} else if (oss[i] instanceof BigInteger) {
								if (fd.getType().equals(Double.class)) {
									fd.set(obj,
											((BigInteger) oss[i]).doubleValue());
								} else if (fd.getType().equals(double.class)) {

									fd.set(obj,
											((BigInteger) oss[i]).doubleValue());

								} else if (fd.getType().equals(byte.class)) {

									fd.set(obj,
											((BigInteger) oss[i]).byteValue());

								} else if (fd.getType().equals(Byte.class)) {

									fd.set(obj,
											((BigInteger) oss[i]).byteValue());

								} else if (fd.getType().equals(long.class)) {

									fd.set(obj,
											((BigInteger) oss[i]).longValue());

								} else if (fd.getType().equals(float.class)) {

									fd.set(obj,
											((BigInteger) oss[i]).floatValue());

								} else if (fd.getType().equals(Float.class)) {
									fd.set(obj,
											((BigInteger) oss[i]).floatValue());
								} else if (fd.getType().equals(Long.class)) {
									fd.set(obj,
											((BigInteger) oss[i]).longValue());
								} else if (fd.getType().equals(Integer.class)) {
									fd.set(obj,
											((BigInteger) oss[i]).intValue());
								} else if (fd.getType().equals(int.class)) {
									fd.set(obj,
											((BigInteger) oss[i]).intValue());
								} else if (fd.getType().equals(Boolean.class)
										|| fd.getType().equals(boolean.class)) {
									if (((BigInteger) oss[i]).intValue() == 1) {
										fd.set(obj, true);
									} else {
										fd.set(obj, false);
									}
								} else {
									fd.set(obj, oss[i]);
								}
							} else {
								if (fd.getType().getSuperclass()
										.getSimpleName()
										.equalsIgnoreCase("enum")) {
									fd.set(obj,
											fd.getType()
													.getDeclaredMethod(
															"valueOf",
															String.class)
													.invoke(null,oss[i]));

								} else {
									fd.set(obj, oss[i]);
								}

							}
						}
						dataList.add(obj);
					} catch (Exception e) {

						e.printStackTrace();
					}

				}
			}

			data.setDataList(dataList);
			return data;
		}
		return new PageInfo<T>(1, 20, 0, new ArrayList());
	}

}
